﻿using System;
using System.IO;
using System.Web;

namespace WebApplication1
{
    public class FileUploader : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            string fileName = HttpContext.Current.Request.QueryString["FileName"].ToString();
            string directorio = HttpContext.Current.Request.QueryString["Dir"].ToString();
            DateTime fecha = DateTime.ParseExact(HttpContext.Current.Request.QueryString["Fecha"].ToString(), "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
            string pathPaciente = HttpContext.Current.Server.MapPath("~\\Imagenes\\") + directorio;
            if (!System.IO.Directory.Exists(pathPaciente))
            {
                System.IO.Directory.CreateDirectory(pathPaciente);
            }
            string pathTratamiento = pathPaciente + "\\" + fecha.ToString("yyyyMMdd");
            if (!System.IO.Directory.Exists(pathTratamiento))
            {
                System.IO.Directory.CreateDirectory(pathTratamiento);
            }
            using (FileStream fs = File.Create(pathTratamiento + "\\" + fileName))
            {
                Byte[] buffer = new Byte[32 * 1024];
                int read = context.Request.GetBufferlessInputStream().Read(buffer, 0, buffer.Length);
                while (read > 0)
                {
                    fs.Write(buffer, 0, read);
                    read = context.Request.GetBufferlessInputStream().Read(buffer, 0, buffer.Length);
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}